<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  
  
    <meta name="keywords" content="前端,Vue.js,JavaScript,Node.js,小程序">
  
  
    <meta name="description" content="GuoYou.Li(李国有)的博客, 用于做学习过程中的笔记、总结以及知识分享">
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>
    微信小程序端开发静默授权功能异步方法 uni-login 改成同步方法 |
    
    种子的信仰</title>
  
    <link rel="shortcut icon" href="/your/favicon.ico">
  
  
<link rel="stylesheet" href="/your/css/style.css">

  
    
<link rel="stylesheet" href="/your/fancybox/jquery.fancybox.min.css">

  
  
<script src="/your/js/pace.min.js"></script>

<meta name="generator" content="Hexo 4.2.1"><link rel="alternate" href="/your/atom.xml" title="种子的信仰" type="application/atom+xml">
</head>

<body>
<main class="content">
  <section class="outer">
  <article id="post-uni-login" class="article article-type-post" itemscope itemprop="blogPost" data-scroll-reveal>

    <div class="article-inner">
        
            <header class="article-header">
                
  
    <h1 class="article-title" itemprop="name">
      微信小程序端开发静默授权功能异步方法 uni-login 改成同步方法
    </h1>
  
  




            </header>
            

                
                    <div class="article-meta">
                        <a href="/your/2022/03/08/uni-login/" class="article-date">
  <time datetime="2022-03-08T15:23:53.000Z" itemprop="datePublished">2022-03-08</time>
</a>
                            
  <div class="article-category">
    <a class="article-category-link" href="/your/categories/%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/">问题解决</a> / <a class="article-category-link" href="/your/categories/%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/">微信小程序</a>
  </div>

                    </div>
                    

                        
                            
    <div class="tocbot"></div>





                                

                                    <div class="article-entry" itemprop="articleBody">
                                        


                                            

                                                
                                                                    <h1 id="一-问题描述"><a href="#一-问题描述" class="headerlink" title="一.问题描述"></a>一.问题描述</h1><h2 id="1-需求"><a href="#1-需求" class="headerlink" title="1.需求"></a>1.需求</h2><p>微信小程序端开发静默授权功能, 在应用生命周期 <code>onLaunch</code> 中获取 <code>memberId</code> 然后存储 <code>localStorage</code> 中, 然后在页面生命周期 <code>onLoad</code> 中需要 <code>memberId</code>, 代码如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// common.js</span></span><br><span class="line">silentAuthorization() &#123;</span><br><span class="line">    <span class="keyword">const</span> extConfig = uni.getExtConfigSync();</span><br><span class="line">    <span class="keyword">const</span> appId = extConfig.appid;</span><br><span class="line">    <span class="keyword">const</span> success = <span class="keyword">async</span> (codeInfo) =&gt; &#123;</span><br><span class="line">        <span class="keyword">const</span> jsCode = codeInfo.code;</span><br><span class="line">        <span class="keyword">const</span> data = <span class="keyword">await</span> vm.$api.wxAuth(&#123; appId, jsCode, <span class="attr">loginMode</span>: <span class="number">1</span> &#125;);</span><br><span class="line">        <span class="keyword">if</span> (data.code !== <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">const</span> &#123; id &#125; = data.data.member;</span><br><span class="line">        uni.setStorageSync(<span class="string">'memberId'</span>, id);</span><br><span class="line">    &#125;;</span><br><span class="line">    uni.login(&#123; success &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// APP.vue</span></span><br><span class="line">onLaunch() &#123;</span><br><span class="line">    <span class="keyword">this</span>.$common.silentAuthorization();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Index.vue</span></span><br><span class="line">onLoad() &#123;</span><br><span class="line">    <span class="keyword">const</span> memberId = uni.getStorageSync(<span class="string">'memberId'</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(memberId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-预期结果"><a href="#2-预期结果" class="headerlink" title="2.预期结果"></a>2.预期结果</h2><p>在 <code>Index.vue</code> 的 <code>onLoad</code> 中能输出 <code>memberId</code> 的值;</p>
<h2 id="3-实际结果"><a href="#3-实际结果" class="headerlink" title="3.实际结果"></a>3.实际结果</h2><p>第一次进入页面, 在 <code>Index.vue</code> 的 <code>onLoad</code> 中未能拿到 <code>memberId</code> 的值, 有了缓存之后打开小程序才能拿到;</p>
<h2 id="4-原因及解决办法"><a href="#4-原因及解决办法" class="headerlink" title="4.原因及解决办法"></a>4.原因及解决办法</h2><p><code>uni.login</code> 是一个异步回调函数, 执行 <code>onLoad</code> 的时候没办法保证 <code>silentAuthorization</code> 已经执行完, 需要将 <code>uni.login</code> 改造为同步函数, 这里需要用到 <code>Promise</code>, 修改后代码如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// common.js</span></span><br><span class="line"><span class="keyword">async</span> silentAuthorization() &#123;</span><br><span class="line">    <span class="keyword">const</span> extConfig = uni.getExtConfigSync();</span><br><span class="line">    <span class="keyword">const</span> appId = extConfig.appid;</span><br><span class="line">    <span class="keyword">const</span> codeInfo = <span class="keyword">await</span> <span class="keyword">this</span>.uniLoginSync();</span><br><span class="line">    <span class="keyword">const</span> jsCode = codeInfo.code;</span><br><span class="line">    <span class="keyword">const</span> data = <span class="keyword">await</span> vm.$api.wxAuth(&#123; appId, jsCode, <span class="attr">loginMode</span>: <span class="number">1</span> &#125;);</span><br><span class="line">    <span class="keyword">if</span> (data.code !== <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">const</span> &#123; id &#125; = data.data.member;</span><br><span class="line">    uni.setStorageSync(<span class="string">'memberId'</span>, id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Index.vue</span></span><br><span class="line"><span class="keyword">async</span> onLoad() &#123;</span><br><span class="line">    <span class="keyword">let</span> memberId = uni.getStorageSync(<span class="string">'memberId'</span>);</span><br><span class="line">    <span class="keyword">if</span> (!memberId) &#123;</span><br><span class="line">        <span class="comment">// 第一次进入小程序没有缓存的时候才会执行</span></span><br><span class="line">        <span class="keyword">await</span> <span class="keyword">this</span>.$common.silentAuthorization();</span><br><span class="line">        memberId = uni.getStorageSync(<span class="string">'memberId'</span>); <span class="comment">// 用 vuex 来管理 memberId 会更加方便</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(memberId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="二-参考"><a href="#二-参考" class="headerlink" title="二.参考"></a>二.参考</h1><p><a href="https://www.xiaoguan.net/posts/show/201" target="_blank" rel="noopener">使用async + await将uni-app中的异步请求同步化</a></p>

                                                                        
                                    </div>
                                    <footer class="article-footer">
                                        <!-- 注释 - 分享按钮 -->
                                        <!-- <a data-url="http://liguoyou.gitee.io/your/2022/03/08/uni-login/" data-id="cl0ia8yje0000ikon7l6uc7hl" class="article-share-link">
                                            分享
                                        </a> -->
                                        
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/your/tags/uniapp/" rel="tag">uniapp</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/your/tags/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/" rel="tag">微信小程序</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/your/tags/%E9%9D%99%E9%BB%98%E6%8E%88%E6%9D%83/" rel="tag">静默授权</a></li></ul>

                                    </footer>

    </div>

    
        
  <nav class="article-nav">
    
      <a href="/your/2022/03/09/good-articles/" class="article-nav-link">
        <strong class="article-nav-caption">前一篇</strong>
        <div class="article-nav-title">
          
            放入收藏夹吃灰吧!
          
        </div>
      </a>
    
    
      <a href="/your/2022/03/07/on-add-to-favorites/" class="article-nav-link">
        <strong class="article-nav-caption">后一篇</strong>
        <div class="article-nav-title">使用 uniapp 开发微信小程序分享及收藏小程序功能</div>
      </a>
    
  </nav>


            

                
                    
                        
  <div class="gitalk" id="gitalk-container"></div>
  <p style="color: #999; font-size: 12px; text-align: center;">
    第三方评论系统 -- Gitalk: 偶尔可能出现加载失败的情况, 您可以选择刷新或者前往 
    <a href="https://github.com/liguoyou/your/issues" target="_blank">issues</a>
    提交和查看评论
  </p>
  
<link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">

  
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

  
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>

  <script type="text/javascript">
    var gitalk = new Gitalk({
      clientID: '2e731d2b04096a7c71ab',
      clientSecret: '41e2e15eb8edebd8efd5a6da558a44d60f33468a',
      repo: 'your',
      owner: 'liguoyou',
      admin: ['liguoyou'],
      // id: location.pathname,      // Ensure uniqueness and length less than 50
      id: md5(location.pathname),
      distractionFreeMode: false,  // Facebook-like distraction free mode
      pagerDirection: 'last'
    })

  gitalk.render('gitalk-container')
  </script>

                            

</article>
</section>
  <footer class="footer">
  <div class="outer">
    <div class="float-right">
      <ul class="list-inline">
  
    <li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
  
    <li><i class="fe fe-bookmark"></i> <span id="busuanzi_value_page_pv"></span></li>
  
</ul>
    </div>
    <ul class="list-inline">
      <li>&copy; 2022 种子的信仰</li>
      <li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
      <li>Theme  <a href="https://github.com/zhwangart/hexo-theme-ocean" target="_blank" rel="noopener">Ocean</a></li>
    </ul>
  </div>
</footer>

</main>
<aside class="sidebar">
  <button class="navbar-toggle"></button>
<nav class="navbar">
  
    <div class="logo">
      <a href="/your/"><img src="/your/images/logo.png" alt="种子的信仰"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/">首页</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/archives">时间轴</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/gallery">相册</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/categories">分类</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/tags">标签</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/about">关于</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="搜索">
        <i class="fe fe-search"></i>
        搜索
      </a>
    </li>
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      <div class="totop" id="totop">
  <i class="fe fe-rocket"></i>
</div>
    </li>
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/your/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="请输入关键词...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
</aside>

<script src="/your/js/jquery-2.0.3.min.js"></script>


<script src="/your/js/jquery.justifiedGallery.min.js"></script>


<script src="/your/js/lazyload.min.js"></script>


<script src="/your/js/busuanzi-2.3.pure.min.js"></script>


  
<script src="/your/fancybox/jquery.fancybox.min.js"></script>




  
<script src="/your/js/tocbot.min.js"></script>

  <script>
    // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
    tocbot.init({
      tocSelector: '.tocbot',
      contentSelector: '.article-entry',
      headingSelector: 'h1, h2, h3, h4, h5, h6',
      hasInnerContainers: true,
      scrollSmooth: true,
      positionFixedSelector: '.tocbot',
      positionFixedClass: 'is-position-fixed',
      fixedSidebarOffset: 'auto',
    });
  </script>


<script src="/your/js/ocean.js"></script>


</body>
</html>